<template>
  <div>
    <input type="file" id="fileUpload" name="file" style="display: none" />
    <el-row class="upload" v-if="false">
      <el-col :span="12">
        <el-upload
          action="http://up-z0.qiniup.com/"
          :http-request="uploadFile"
          multiple
          :disabled="disabled"
          accept=".jpg,.jpeg,.png,.gif,.JPG,.JPEG"
          :show-file-list="false">
           <div class="item" slot="trigger"><i class="upload-icon el-icon-picture-outline"></i>上传图片</div>
         </el-upload>
      </el-col>
      <el-col :span="12">
        <el-upload
          action="http://up-z0.qiniup.com/"
          multiple
          :disabled="disabled"
          :http-request="uploadFile"
          accept=".pdf,.doc,.docx,.ppt,pptx"
          :show-file-list="false">
          <div class="item" slot="trigger"> <i class="upload-icon el-icon-document-checked"></i>上传文件</div>
        </el-upload>
      </el-col>
    </el-row>
    <editor id="tinymceEditor" :disabled="disabled" :init="tinymceInit" v-model="innerValue"></editor>

  </div>
</template>
<script>
  import tinymce from 'tinymce'
  import Editor from '@tinymce/tinymce-vue'
  import 'tinymce/icons/default/icons';
  import 'tinymce/themes/silver'
  import 'tinymce/plugins/advlist/plugin.min'
  import 'tinymce/plugins/table/plugin.min'
  import 'tinymce/plugins/lists/plugin.min'
  import 'tinymce/plugins/paste/plugin.min'
  import 'tinymce/plugins/preview/plugin.min'
  import 'tinymce/plugins/fullscreen/plugin.min'
  import 'tinymce/plugins/image/plugin.min'
  import 'tinymce/plugins/link/plugin.min'
  import 'tinymce/plugins/code/plugin.min'
  import axios from 'axios'
  import { getUploadToken } from "@/api/system/oss"
  const webPrefix=process.env.NODE_ENV === "production" ? "/" : "/"
  export default {
    name: 'TinymceEditor',
    props:{
      value:String,
      disabled:Boolean
    },
    components: {
      'editor': Editor
    },
    data () {
      return {
        tinymceFlag: 1,
        tinymceInit: {},
        token:'',
        innerValue:this.value
      }
    },
    methods: {
      // 插入图片至编辑器
      insertImage(res, file) {
        tinymce.execCommand('mceInsertContent', false, `<img src="${res.fileUrl}" style="width:80%">`)
      },
      insertFile(res, file) {
        tinymce.execCommand('mceInsertContent', false, `<a target="_blank" href="${res.fileUrl}">${file.name}</a>`)
      },
      getContent() {
        return this.htmlEncode(this.content);
      },
      setContent(content) {
        this.content = this.htmlDecode(content);
      },
      htmlEncode(str) {
        str = str.replace(/&/g, "&amp;");
        str = str.replace(/</g, "&lt;");
        str = str.replace(/>/g, "&gt;");
        str = str.replace(/ /g, "&nbsp;");
        str = str.replace(/"/g, '&quot;');
        return str;
      },
      //解码
      htmlDecode(str) {
        str = str.replace(/&amp;/g, "&");
        str = str.replace(/&lt;/g, "<");
        str = str.replace(/&gt;/g, ">");
        str = str.replace(/&amp;nbsp;/g, " ");
        str = str.replace(/&quot;/g, "'");
        return str;
      },
      uploadToken(){
        return new Promise(function (resolve,reject) {
          getUploadToken().then(res => {
            if (res.code == 200) {
              resolve(res.data);
            } else {
              reject();
              this.$message({
                message: "获取凭证出错！",
                type: "error",
                center: true
              });
            }
          })
        })
      },
      uploadFile(raw) {
        this.uploadToken().then(token => {
          let formData = new FormData();
          formData.append("file", raw.file);
          formData.append("token", token.token);
          //获取后缀名
          let ext = raw.file.name.substr(raw.file.name.lastIndexOf(".") + 1);
          formData.append("key", token.fileName + "." + ext);
          let config = {
            headers: {
              'Content-Type': 'multipart/form-data'
            }
          };
          const loading = this.$loading({
            lock: true,//lock的修改符--默认是false
            text: '上传中...',//显示在加载图标下方的加载文案
            spinner: 'el-icon-loading',//自定义加载图标类名
            background: 'rgba(0, 0, 0, 0.7)',//遮罩层颜色
          });
          axios.post("http://up-z0.qiniup.com/", formData, config).then(res => {
            loading.close()
            if (res.status == 200) {
              var dataStr = res.data;
              dataStr = dataStr.substring(0, dataStr.length - 2);
              var dataStr = JSON.parse(dataStr);
              var type=raw.file.name.substring(raw.file.name.lastIndexOf('.')+1)
              if(".jpg,.jpeg,.png,.gif,.JPG,.JPEG".indexOf(type)!=-1){
                this.insertImage(dataStr,raw.file);
              }else{
                this.insertFile(dataStr,raw.file)
              }
            } else {
              this.$message({
                message: "上传出错，请重试！",
                type: "error",
                center: true
              });
            }
          })
        })
      },
    },
    created () {
      this.tinymceInit = {
        skin_url: webPrefix+'tinymce/skins/ui/oxide',
        language_url: webPrefix+`tinymce/langs/zh_CN.js`,
        content_css: webPrefix+"tinymce/skins/ui/oxide/content.css",
        language: 'zh_CN',
        height: document.body.offsetHeight - 400,
        browser_spellcheck: true, // 拼写检查
        branding: false, // 去水印
        convert_urls :false,
        statusbar: false, // 隐藏编辑器底部的状态栏
        paste_data_images: true, // 允许粘贴图像
        menubar: false, // 隐藏最上方menu
        plugins: 'advlist table lists paste preview fullscreen image link code',
        toolbar: 'undo redo | fontselect fontsizeselect forecolor backcolor bold italic underline strikethrough | alignleft aligncenter alignright alignjustify | link unlink quicklink h2 h3 blockquote | table numlist bullist | preview fullscreen undo code',
      }
    },
    mounted () {
    },
    watch:{
      value(newValue) {
        this.innerValue = newValue
      },
      innerValue(value){
        this.$emit("input",value)
      }
    }
  }
</script>

<style>
  .tox-silver-sink{z-index:10000!important;}
  .upload .upload-icon{font-size:30px}
  .upload .el-col{display: flex;flex-direction:column;align-items: center}
  .upload{background-color:#f8f8f8;padding-top: 10px}
  .upload .item{display: flex;flex-direction:column;align-items: center;cursor: pointer;
    font-size: 14px;padding-bottom: 10px}
</style>
